package sk.ygor.raynor.client.http;

import com.google.gwt.json.client.JSONValue;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.http.client.*;
import sk.ygor.raynor.client.service.JSONService;

/**
 * User: ygor
 * Date: 1.1.2009
 * Time: 19:51:50
 */
public class HttpPostJSONServiceInvoker implements JSONService.Invoker {

    private final String url;

    public HttpPostJSONServiceInvoker(String url) {
        this.url = url;
    }

    public void invoke(String serviceName, String methodName, final AsyncCallback<JSONValue> callback, Parameter... parameters) {
        RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, url);
        try {
            rb.setHeader("Content-Type", "application/x-www-form-urlencoded");
            StringBuilder sb = new StringBuilder();
            sb.append("serviceName=").append(serviceName);
            sb.append("&methodName=").append(methodName);
            for (Parameter parameter : parameters) {
                sb.append("&serviceParameters[" + parameter.name + "]=").append(parameter.value.toString());
            }
//            System.out.println("RAW REQUEST " + sb);
            rb.sendRequest(sb.toString(), new RequestCallback() {
                public void onResponseReceived(Request request, Response response) {
                    try {
                        String rawResponse = response.getText();
//                        System.out.println("RAW RESPONSE: " + rawResponse);
                        JSONValue parsedResponse;
                        try {
                            parsedResponse = JSONParser.parse(rawResponse);
                        } catch (Exception e) {
//                            System.out.println("PARSE ERROR: " + e.toString());
                            throw new HttpPostJSONServiceException(rawResponse, e);
                        }
                        HttpPostJSONServiceResult result = new HttpPostJSONServiceResult(parsedResponse);
                        if (HttpPostJSONServiceResult.RESULT.equals(result.getType())) {
//                            System.out.println("PARSED RESULT: " + result.getResult());
                            callback.onSuccess(result.getResult());
                        } else {
//                            System.out.println("PARSED EXCEPTION: " + result.getResult());
                            throw new Exception(result.getExceptionMessage());
                        }
                    } catch (Exception ex) {
                        callback.onFailure(ex);
                    }
                }

                public void onError(Request request, Throwable ex) {
                    callback.onFailure(ex);
                }
            });
        } catch (RequestException ex) {
            callback.onFailure(ex);
        }
    }
}
